//
//  PhotoBrowserCell.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/3/2.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

// MARK: - PhotoBrowserCellDelegate
protocol PhotoBrowserCellDelegate: NSObjectProtocol {
    func photoBrowserCellDidClickImage()
}

// MARK: - 照片查看 Cell
class PhotoBrowserCell: UICollectionViewCell {
    
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    /// 点击图像监听方法
    @objc private func clickImage() {
        photoDelegate?.photoBrowserCellDidClickImage()
    }
    
    var imageURL:URL?{
        didSet{
            guard let url = imageURL else {
                return
            }
            
            // 重置滚动视图
            resetScrollView()
            
            imageView.image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: url.absoluteString)
            imageView.sizeToFit()
            imageView.center = scrollView.center
            
            imageView.sd_setImage(with: middleUrl(url: url),
                                  placeholderImage: nil,
                                  options: [SDWebImageOptions.retryFailed,SDWebImageOptions.refreshCached], progress: { (current, total, _) in
                                    
            }) { (image, _, _, _) in
                if image == nil {
                    SVProgressHUD.showInfo(withStatus: "加载图像失败")
                    return
                }
                
                self.setPostion(image: image!)
            }
        }
    }
    
    /// 重置滚动视图
    private func resetScrollView(){
        imageView.transform = CGAffineTransform.identity
        
        scrollView.contentInset = UIEdgeInsets.zero
        scrollView.contentOffset = CGPoint.zero
        scrollView.contentSize = CGSize.zero
    }
    
    /// 设置图像位置
    private func setPostion(image:UIImage){
        let size  = self.displaySize(image: image)
        scrollView.contentSize = size
        
        if size.height > scrollView.bounds.height{
            imageView.frame = CGRect(origin: CGPoint.zero, size: size)
        }else{
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            let y = (scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
    }
    
    //根据 scrollview 的宽度计算等比例缩放之后的图片尺寸
    private func displaySize(image:UIImage) -> CGSize{
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
    /// - returns: 中图 URL
    private func middleUrl(url:URL) -> URL{
        var urlString = url.absoluteString
        
        urlString = urlString.replacingOccurrences(of: "/thumbnail/", with: "/bmiddle/")
        
        return URL(string: urlString)!
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        // 2. 设置位置
        var rect = bounds
        rect.size.width = rect.size.width - 20
        scrollView.frame = bounds
        // 3. 设置代理
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        // 4. 添加手势识别
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowserCell.clickImage))
        imageView.addGestureRecognizer(tap)
        
    }
    
    //懒加载控件
    /// 滚动视图
    lazy var scrollView:UIScrollView = UIScrollView()
    /// 图像视图
    lazy var imageView:UIImageView = UIImageView()
    
    private lazy var placeholder:UIImageView = UIImageView()
}

extension PhotoBrowserCell:UIScrollViewDelegate{
    /// 返回要缩放的视图
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    /// 缩放完成后才回被调用
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        offsetY = offsetY < 0 ? 0 : offsetY
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
}
